'use strict';
var io = require('socket.io')();
var users = [];
io.on('connection',function(socket){

  //失去链接
  socket.on('disconnect',function(){
    users.splice(socket.userIndex,1);
    if(socket.nickName != null){
      socket.broadcast.emit('system',socket.nickName, users.length, 'logout');
    }
  });

  //登录操作
  socket.on('login',function(data){
    if(users.indexOf(data) > -1){
      socket.emit('nickExisted');
    }else{
      socket.userIndex = data.length;
      socket.nickName = data;
      users.push(data);
      socket.emit('loginSuccess');
      io.sockets.emit('system',data,users.length,'login');
    }
  });

  //发送聊天信息
  socket.on('send',function(data){
    socket.broadcast.emit('newMsg', socket.nickName,data);
  });
});

module.exports = io;